package com.android.delivery.activity.siji;

import android.content.Context;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.View;
import android.widget.TextView;

import com.android.delivery.R;
import com.android.delivery.activity.fragment.scan.CaptureActivityHandler;
import com.android.delivery.activity.fragment.scan.CaptureFragment;
import com.android.delivery.api.ApiService;
import com.android.delivery.base.BaseActivity;
import com.android.delivery.callback.DialogCallback;
import com.android.delivery.callback.LzyResponse;
import com.android.delivery.constant.Constants;
import com.android.delivery.dialog.SanSuccDialog;
import com.android.delivery.entity.Scan;
import com.android.delivery.util.ToastUtils;
import com.lzy.okgo.model.Response;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import butterknife.BindView;

/**
 * Initial the camera
 * <p>
 * 默认的二维码扫描Activity
 */
public class CaptureActivity extends BaseActivity {

    //扫码上车
    public static final int TYPE_SCAN_ON_CAR = 0;
    //扫码下车
    public static final int TYPE_SCAN_OFF_CAR = 1;
    //扫码配送
    public static final int TYPE_SCAN_DISPATCH = 2;

    @BindView(R.id.tv_scjs)
    TextView mTvScjs;

    @BindView(R.id.tv_jrjs)
    TextView mTvJrjs;

    @BindView(R.id.tv_no)
    TextView mTvOrderNo;

    @BindView(R.id.tv_type)
    TextView mTvType;

    @BindView(R.id.tv_start_node)
    TextView mTvStartNode;

    @BindView(R.id.tv_receiving_node)
    TextView mTvReceNode;

    private CaptureFragment captureFragment;
    private Handler mHandler = new Handler();
    private int mType;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_scan;
    }

    @Override
    protected void init(Bundle savedInstanceState, View container) {
        mType = getIntent().getIntExtra(Constants.TYPE, 0);

        if (mType == TYPE_SCAN_ON_CAR) {
            setMainTitle("扫码上车");
        } else if (mType == TYPE_SCAN_OFF_CAR) {
            setMainTitle("扫码下车");
        } else if (mType == TYPE_SCAN_DISPATCH) {
            setMainTitle("扫码配送");
        }
        captureFragment = new CaptureFragment();
        captureFragment.setAnalyzeCallback(analyzeCallback);

        getSupportFragmentManager().beginTransaction().replace(R.id.fl_zxing_container, captureFragment).commit();
    }

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
//            Intent resultIntent = new Intent();
//            Bundle bundle = new Bundle();
//            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_SUCCESS);
//            bundle.putString(CodeUtils.RESULT_STRING, result);
//            resultIntent.putExtras(bundle);
//            CaptureActivity.this.setResult(RESULT_OK, resultIntent);
//            CaptureActivity.this.finish();
//            getSoundPool(CaptureActivity.this).play(1,1, 1, 0, 0, 1);
//            vibrate();
            scanSuccRequest(result);
            continueScan();
        }

        @Override
        public void onAnalyzeFailed() {
//            Intent resultIntent = new Intent();
//            Bundle bundle = new Bundle();
//            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
//            bundle.putString(CodeUtils.RESULT_STRING, "");
//            resultIntent.putExtras(bundle);
//            CaptureActivity.this.setResult(RESULT_OK, resultIntent);
//            CaptureActivity.this.finish();
            ToastUtils.showShort(CaptureActivity.this, "扫码失败");
            continueScan();
        }
    };

    /**
     * 继续扫描
     */
    private void continueScan() {
        if (mHandler != null) {
            mHandler.removeCallbacks(mContinueRunnable);
            mHandler.postDelayed(mContinueRunnable, 3000);
        }
    }

    /**
     * Desc:扫描成功震动
     * <p>
     * Author: [李豫]
     * Date: 2019-01-02
     * Update Time:
     * Update Comments:
     */
    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    private SoundPool mSoundPool;

    public SoundPool getSoundPool(Context context) {
        if (mSoundPool == null) {
            mSoundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
            mSoundPool.load(context, R.raw.warning, 1);
        }
        return mSoundPool;
    }

    private void scanSuccRequest(String orderNo) {
        if (mType == TYPE_SCAN_ON_CAR) {
            ApiService.transport_scan(this, orderNo, 0, new DialogCallback<LzyResponse<Scan>>() {
                @Override
                public void onSuccess(Response<LzyResponse<Scan>> response) {
                    setResult(RESULT_OK);
                    ToastUtils.showShort(CaptureActivity.this, "扫码成功");
                    showScanSucc(response.body().data);
                }

                @Override
                public void onError(Response<LzyResponse<Scan>> response) {
                    super.onError(response);
                    continueScan();
                }
            });
        } else if (mType == TYPE_SCAN_OFF_CAR) {
            ApiService.transport_scan_down(this, orderNo, new DialogCallback<LzyResponse<Scan>>() {
                @Override
                public void onSuccess(Response<LzyResponse<Scan>> response) {
                    setResult(RESULT_OK);
                    ToastUtils.showShort(CaptureActivity.this, "扫码成功");
                    showScanSucc(response.body().data);
                }

                @Override
                public void onError(Response<LzyResponse<Scan>> response) {
                    super.onError(response);
                    continueScan();
                }
            });
        } else if (mType == TYPE_SCAN_DISPATCH) {
            ApiService.deliveryTake(this, orderNo, new DialogCallback<LzyResponse<Scan>>() {
                @Override
                public void onSuccess(Response<LzyResponse<Scan>> response) {
                    setResult(RESULT_OK);
                    ToastUtils.showShort(CaptureActivity.this, "扫码成功");
                    showScanSucc(response.body().data);
                }

                @Override
                public void onError(Response<LzyResponse<Scan>> response) {
                    super.onError(response);
                    continueScan();
                }
            });
        }
    }

    private void showScanSucc(Scan scan) {
        if (scan != null){
            mTvScjs.setText(String.valueOf(scan.getCurrentQuantity()));
            mTvJrjs.setText(String.valueOf(scan.getTodayQuantity()));
            mTvOrderNo.setText(scan.getLogisticsNo());
            if (scan.getLogisticsType() ==1){
                mTvType.setText("速配寄件");
            }else if (scan.getLogisticsType() == 2){
                mTvType.setText("零担寄件");
            }else {
                mTvType.setText("同城代寄");
            }
            mTvStartNode.setText(scan.getSourceLocationName());
            mTvReceNode.setText(scan.getTargetLocationName());
        }
    }

    private Runnable mContinueRunnable = new Runnable() {
        @Override
        public void run() {
            if (captureFragment != null) {
                CaptureActivityHandler handler = captureFragment.getHandler();
                if (handler != null) {
                    handler.restartPreviewAndDecode();
                }
            }
        }
    };

    @Override
    protected void onDestroy() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }
}